import React, { useState } from 'react';
import { View, Text, TouchableOpacity, Modal, StyleSheet, FlatList } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { Colors } from '../constants/colors';
import { getPlatformSelectorStyle } from '../constants/androidStyles';

export interface Option { label: string; value: string; }

interface Props {
  label: string;
  value: string;
  placeholder?: string;
  options: Option[];
  onChange: (value: string) => void;
  variant?: 'stacked' | 'card';
}

export default function SelectField({ label, value, placeholder, options, onChange, variant = 'card' }: Props) {
  const [visible, setVisible] = useState(false);

  const selected = options.find(o => o.value === value)?.label ?? '';

  return (
    <View style={variant === 'card' ? styles.cardContainer : styles.container}>
      {variant !== 'card' ? (
        <>
          <Text style={styles.label}>{label}</Text>
          <TouchableOpacity style={[styles.selector, getPlatformSelectorStyle()]} activeOpacity={0.8} onPress={() => setVisible(true)}>
            <Text style={[styles.text, !selected && styles.placeholder, { flex: 1 }]}>
              {selected || placeholder || '請選擇'}
            </Text>
            <Ionicons name="chevron-down" size={18} color={Colors.gray[400]} style={{ marginLeft: 8 }} />
          </TouchableOpacity>
        </>
      ) : (
        <View style={styles.leftRow}>
          <Text style={styles.leftLabel}>{label}</Text>
          <TouchableOpacity style={[styles.selector, { flex: 1 }, getPlatformSelectorStyle()]} activeOpacity={0.8} onPress={() => setVisible(true)}>
            <Text style={[styles.text, !selected && styles.placeholder, { flex: 1 }]}>
              {selected || placeholder || '請選擇'}
            </Text>
            <Ionicons name="chevron-down" size={18} color={Colors.gray[400]} style={{ marginLeft: 8 }} />
          </TouchableOpacity>
        </View>
      )}


      <Modal visible={visible} transparent animationType="fade" onRequestClose={() => setVisible(false)}>
        <View style={styles.overlay}>
          <View style={styles.sheet}>
            <Text style={styles.sheetTitle}>{label}</Text>
            <FlatList
              data={options}
              keyExtractor={(item) => item.value}
              renderItem={({ item }) => (
                <TouchableOpacity
                  style={styles.optionRow}
                  onPress={() => { onChange(item.value); setVisible(false); }}
                >
                  <Text style={styles.optionText}>{item.label}</Text>
                </TouchableOpacity>
              )}
            />
            <TouchableOpacity style={styles.cancelBtn} onPress={() => setVisible(false)}>
              <Text style={styles.cancelText}>取消</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { backgroundColor: Colors.gray[100], borderRadius: 12, paddingHorizontal: 16, paddingVertical: 12 },
  cardContainer: { backgroundColor: Colors.white, borderRadius: 16, paddingHorizontal: 16, paddingVertical: 14, borderWidth: 1, borderColor: Colors.gray[200] },
  label: { color: Colors.gray[400], marginBottom: 6, fontSize: 14 },
  leftRow: { flexDirection: 'row', alignItems: 'center' },
  leftLabel: { width: 85, color: Colors.gray[600], fontSize: 14 }, // 修改为与 InputField 一致的宽度
  selector: {
    backgroundColor: Colors.white,
    borderRadius: 10,
    paddingHorizontal: 0,
    paddingVertical: 12,
    minHeight: 44, // 确保安卓上有足够的高度
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    flex: 1 // 添加这一行，确保填充剩余空间
  },
  text: { color: Colors.black, fontSize: 16 },
  placeholder: { color: Colors.gray[400] },
  overlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.4)', alignItems: 'center', justifyContent: 'center' },
  sheet: { width: '86%', backgroundColor: Colors.white, borderRadius: 16, paddingVertical: 16, maxHeight: '70%' },
  sheetTitle: { fontSize: 16, fontWeight: '700', color: Colors.gray[700], textAlign: 'center', marginBottom: 8 },
  optionRow: { paddingHorizontal: 16, paddingVertical: 14, borderBottomWidth: 1, borderBottomColor: Colors.gray[200] },
  optionText: { fontSize: 16, color: Colors.gray[700] },
  cancelBtn: { marginTop: 6, alignSelf: 'center', backgroundColor: Colors.gray[200], paddingHorizontal: 24, paddingVertical: 10, borderRadius: 12 },
  cancelText: { color: Colors.gray[600], fontWeight: '600' },
});

